<?php
/**
 * 极简随手记
 * ============================================================================
 * 版权所有 2024-2099 www.alipay168.cn，并保留所有权利。
 * 网站地址: https://www.alipay168.cn
 * ============================================================================
 * Author: 草上飞
 * Email: wei@alipay16.cn
 * QQ: 2719875001
 * Date: 2025/5/3
 * 描述:
 */

namespace app\result\extend;

use app\model\user\User;
use app\result\BaseResult;
use app\result\LockResult;
use app\result\UserResult;
use think\facade\Db;

class StaffResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new User();
    }


    public function list($user_id, $args = []): array
    {
        $page = $args['page'] ?? 1;
        $limit = $args['limit'] ?? 10;
        $keyword = $args['keywords'] ?? '';
        $where = [
            ['parent_id', '=', $user_id]
        ];
        $status = $args['status'] ?? '';
        if ($keyword) {
            $where[] = ['username|account|remark', 'like', "%$keyword%"];
        }

        if (!empty($status)) {
            switch ($status) {
                case 1:
                    $where[] = ['status', '=', 0];
                    break;
                case 2:
                    $where[] = ['status', '=', -1];
                    break;
            }
        }
        $filed = 'user_id,user_code,avatar,username,account,remark,status,created_at,updated_at,last_active_time';
        $data = $this->model->data_list($where, $filed, 'user_id desc', $page, $limit);
        if ($data) {
            foreach ($data as &$v) {
                $v['status_desc'] = self::_status_desc($v['status']);
                $v['buttons'] = self::_buttons($v, $user_id);
            }
            unset($v);
        }

        return self::success_return('success', [
            'list' => $data,
        ]);
    }


    private static function _buttons($data, $user_id): array
    {
        $buttons = [
            'edit' => 1,//编辑
            'delete' => 0,//删除
        ];

        return $buttons;
    }

    private static function _status_desc($status): string
    {
        $status_desc = [
            0 => '正常',
            -1 => '已禁用',
        ];
        return $status_desc[$status] ?? '未知';
    }

    public function get($user_id, $args = []): array
    {
        $id = $args['id'] ?? 0;
        if (!$id) {
            return self::error_return('数据错误');
        }
        $data = $this->model->data_get(['user_id' => $id, 'parent_id' => $user_id], 'user_id,user_code,avatar,username,account,status');
        $data['status_desc'] = self::_status_desc($data['status']);
        $data['buttons'] = self::_buttons($data, $user_id);
        if ($data['status'] == -1) {
            $data['status'] = true;
        } else {
            $data['status'] = false;
        }

        return self::success_return('success', [
            'info' => $data,
        ]);
    }

    public function save($user_id, $args): array
    {
        $id = intval($args['id'] ?? 0);
        $username = $args['username'] ?? '';
        $account = $args['account'] ?? '';
        $password = $args['password'] ?? '';
        $remark = $args['remark'] ?? '';
        $status = intval($args['status'] ?? 0);
        if ($status) {
            $status = -1;//禁用
        }

        if (empty($account)) {
            return $this->error_return('登录账号不能为空');
        }

        if (mb_strlen($remark, 'utf-8') > 200) {
            return self::error_return('备注不能超过200字');
        }

        if ($id) {
            $data = $this->model->data_get(['user_id' => $id, 'parent_id' => $user_id]);
            if (!$data) {
                return self::error_return('数据不存在');
            }
        }


        $hasData = $this->model->where([['account', '=', $account]])->column('user_id');
        if (!empty($hasData) && !empty($id) && ($hasData[0] != $id || count(array_unique($hasData)) > 1)) {
            return self::error_return('登录账号已存在，请修改');
        } elseif ($hasData && empty($id)) {
            return self::error_return('登录账号已存在，请修改');
        }
        if (empty($id) && empty($args['password'])) {
            return $this->error_return('密码不能为空');
        }
        $baseData = [
            'parent_id' => $user_id,
            'avatar' => request()->domain() . '/static/image/default_image.png',
            'status' => $status,
            'remark' => $remark,
            'username' => $username,
            'account' => $account,
        ];
        if ($password) {
            //判断密码不可以小于6位，大于16位
            if (strlen($args['password']) < 6 || strlen($args['password']) > 16) {
                return $this->error_return('密码长度为6-16位');
            }
            //密码只能是数字、字母、下划线
            /*if (!preg_match('/^[0-9a-zA-Z_]+$/', $args['password'])) {
                return $this->error_return('密码只能是数字、字母、下划线');
            }*/
            $args['password'] = trim($args['password']);
            $salt = substr(md5(uniqid('', true)), 0, 10);
            $password = md5($args['password'] . $salt);

            $baseData['password'] = $password;
            $baseData['salt'] = $salt;
        }

        $resultUser = new UserResult();
        if (empty($args['username'])) {
            $baseData['username'] = $resultUser->getNickname();
        }
        if (empty($id)) {
            $user_code = $resultUser->get_user_code();
            $baseData['user_code'] = $user_code;
        }

        //判断是不是email
        if (filter_var($account, FILTER_VALIDATE_EMAIL)) {
            $args['email'] = $account;
            if ($this->model->data_get(['email' => $account])) {
                return $this->error_return('邮箱已存在');
            }
            $baseData['email'] = $account;
        }
        $lock = md5($account . $user_id);
        if (!LockResult::logck_by_second($lock, 3, true)) {
            return self::error_return('正在执行，请稍后再试');
        }

        Db::startTrans();
        try {
            if ($id > 0) {
                $res = (new User())->data_update(['user_id' => $id], $baseData);
                if (!$res) {
                    throw new \Exception('修改失败');
                }
            } else {
                $user_id = $this->model->data_add($baseData);
                if (!$user_id) {
                    throw new \Exception('保存账号失败');
                }
            }

        } catch (\Exception $e) {
            Db::rollback();
            return self::error_return($e->getMessage());
        }
        Db::commit();

        return self::success_return('保存成功');
    }


}
